package com.youxue.controller;

import com.alibaba.fastjson.JSONObject;
import com.cangshi.permission.entity.CorrectJSONObject;
import com.cangshi.permission.entity.UserSubject;
import com.youxue.entity.*;
import com.youxue.permission.saver.SubjectHolder;
import com.youxue.service.DynamicService;
import com.youxue.service.InteractionService;
import com.youxue.service.UserFabulousService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by ACER on 2018/1/20.
 */
@Controller
@RequestMapping("/dynamic")
public class DynamicController {
    @Autowired
    DynamicService dynamicService;

    @ResponseBody
    @RequestMapping(value = "/test", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String selectId(@RequestParam(required = false) int danamicId) {

        CorrectJsonObject correctJsonObject = new CorrectJsonObject("查询成功");
        correctJsonObject.setData(dynamicService.select(danamicId));
        return JSONObject.toJSONString(correctJsonObject);
    }

    @Autowired
    InteractionService interactionService;

    /**
     * （re）
     * 分页展示所有的动态
     *
     * @param page
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/showAllByPage", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showThinkCircle(@RequestParam(required = false) Integer page) {
        //每次查询数据条数
        int pagesize = 5;
        //数据条数
        int totalRecord = dynamicService.selectTotalRecord();
        //查询结果页数
        int resultAllpage;

        if (totalRecord % pagesize == 0) {
            resultAllpage = totalRecord / pagesize;
        } else resultAllpage = totalRecord / pagesize + 1;

        if (0 == totalRecord || 0 == page) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(101, "请求页数或数据为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
        if (page > resultAllpage) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(102, "请求页数超额");
            return JSONObject.toJSONString(errorJsonObject);
        }
        if (page < 1) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(103, "请求页数不足");
            return JSONObject.toJSONString(errorJsonObject);
        }

        List<Dynamic> dynamics = dynamicService.showAllDynamicByPage((page - 1) * pagesize, pagesize);
        for (Dynamic dynamic : dynamics) {
            //将每条动态的直接评论总条数放入动态中
            dynamic.setAllCommentCount(interactionService.showADynamicAllCommentCount(dynamic.getDynamicId()));
        }

        CorrectJsonObject correctJsonObject = new CorrectJsonObject("用户动态信息获取成功");
        correctJsonObject.setData(dynamics);
        correctJsonObject.put("allPage", resultAllpage);
        return correctJsonObject.toString();
    }


    /**
     * (no)
     * 查询所有消息列表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/newsList", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showAllNews() {
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();

        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        if (userId < 0) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(102, "用户id不正确");
            return JSONObject.toJSONString(errorJsonObject);
        }

        List<Dynamic> dynamics = dynamicService.showNews(userId);
        CorrectJsonObject correctJsonObject = new CorrectJsonObject("所有信息获取成功");
        correctJsonObject.setData(dynamics);
        return correctJsonObject.toString();
    }

    /**
     * （no）
     * 读取未读消息
     *
     * @param interactionId
     * @return
     */


    @ResponseBody
    @RequestMapping(value = "/readNews", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    String readNews(@RequestParam(required = false) Integer interactionId) {
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();

        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        if (userId < 0 || interactionId < 0) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(102, "请求id不正确");
            return JSONObject.toJSONString(errorJsonObject);
        }

        dynamicService.readNews(userId, interactionId);

        return new CorrectJSONObject("消息读取成功").toString();

    }

    /**
     * (re)
     * 查看一条动态详情
     *
     * @param dynamicId
     * @return
     */

    @ResponseBody
    @RequestMapping(value = "/oneDynamic/detail", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showOneDynamic(@RequestParam(required = false) Integer dynamicId) {


        if (null == dynamicId) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(102, "参数不完整");
            return JSONObject.toJSONString(errorJsonObject);
        }

        Dynamic dynamic = dynamicService.showOneDynamic(dynamicId);
        if (null == dynamic) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(103, "请求动态id不存在");
            return JSONObject.toJSONString(errorJsonObject);
        }

        CorrectJsonObject correctJsonObject = new CorrectJsonObject("该条动态信息获取成功");
        correctJsonObject.setData(dynamic);
        return correctJsonObject.toString();

    }

    /***(no)
     * 查看一个动态所有评论
     * @param dynamicId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/interaction/detail", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    String showAllReview(@RequestParam(required = false) Integer dynamicId) {


        if (dynamicId < 0) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(102, "请求id不正确");
            return JSONObject.toJSONString(errorJsonObject);
        }

        Dynamic dynamic = dynamicService.showAllReview(dynamicId);
        if (null == dynamic) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(103, "暂无评论");
            return JSONObject.toJSONString(errorJsonObject);
        }

        CorrectJsonObject correctJsonObject = new CorrectJsonObject("该条动态的所有评论信息获取成功");
        correctJsonObject.setData(dynamic);
        return correctJsonObject.toString();

    }


    /**
     * （re）
     * 添加动态
     *
     * @param dynamic
     * @return
     */

    @ResponseBody
    @RequestMapping(value = "/add/adynamic", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    String addDynamic(@RequestBody(required = false) Dynamic dynamic) {


        //判断dynamic参数是否为空
        if (null == dynamic) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(104, "参数对象为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
        if (null == dynamic.getDynamicTitle() || null == dynamic.getDynamicContent() || "".equals(dynamic.getDynamicContent()) || "".equals(dynamic.getDynamicTitle())) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(105, "动态标题、内容不可为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();

        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        //设置动态发布者id
        dynamic.setDynamicUserId(userId);

        int result = dynamicService.insertDynamic(dynamic);
        if (1 != result) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(106, "发布失败，请重试");
            return JSONObject.toJSONString(errorJsonObject);
        }
        return new CorrectJSONObject("动态发布成功").toString();

    }

    @Autowired
    UserFabulousService userFabulousService;

    /**
     * （re）
     * 点赞
     *
     * @param dynamicId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/giveLike", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String addDynamic(@RequestParam(required = false) Integer dynamicId) {

        if (null == dynamicId) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(105, "未传入id");
            return JSONObject.toJSONString(errorJsonObject);
        }
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();

        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        UserFabulous userFabulous = new UserFabulous();
        userFabulous.setUserId(userId);
        userFabulous.setDynamicId(dynamicId);
        UserFabulous fabulous = userFabulousService.show(userFabulous);
        if (null == fabulous) {
            //插入点赞记录
            int result = userFabulousService.add(userFabulous);
            if (1 == result) {
                //添加点赞数+1
                dynamicService.giveLike(dynamicId);
                return new CorrectJSONObject("点赞成功").toString();

            } else {
                ErrorJsonObject errorJsonObject = new ErrorJsonObject(108, "点赞失败");
                return JSONObject.toJSONString(errorJsonObject);
            }
        } else {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(106, "已经赞过了");
            return JSONObject.toJSONString(errorJsonObject);
        }


    }

    /**
     * 展示登录用户点赞列表
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/show/likes", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showLikes() {
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();

        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        List<UserFabulous> userFabulousList=new ArrayList<UserFabulous>();
        userFabulousList=userFabulousService.showAUserAllFabulous(userId);
        CorrectJsonObject correctJsonObject = new CorrectJsonObject("用户点赞列表查询成功");
        correctJsonObject.setData(userFabulousList);
        return JSONObject.toJSONString(correctJsonObject);
    }

    /**
     * 查询一个用户发表过的所有动态列表（其中allCommentCount代表该条动态所有评论总数）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/show/alldynamics", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String addDynamic() {
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();

        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        List<Dynamic> dynamicList = new ArrayList<Dynamic>();
        dynamicList = dynamicService.showAUserListDynamics(userId);
        if (dynamicList.size() == 0) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(110, "动态空空如也");
            return JSONObject.toJSONString(errorJsonObject);
        }
        //将每条动态评论总数放入动态对象中
        for (Dynamic dynamic : dynamicList) {
            dynamic.setAllCommentCount(interactionService.showADynamicAllCommentCount(dynamic.getDynamicId()));
        }
        CorrectJsonObject correctJsonObject = new CorrectJsonObject("查询成功");
        correctJsonObject.setData(dynamicList);
        return JSONObject.toJSONString(correctJsonObject);
    }


    /**
     * （未测试）
     * 用户删除一条动态
     *
     * @param dynamicId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete/adynamic", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String deleteDynamic(@RequestParam(required = false) Integer dynamicId) {
        if (null == dynamicId) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(111, "未传入dynamicId");
            return JSONObject.toJSONString(errorJsonObject);
        }
        int result = dynamicService.deleteADynamic(dynamicId);
        if (1 == result) {
            //关于该动态的所有评论、回复删除
            interactionService.deleteListInteractions(dynamicId);
            CorrectJsonObject correctJsonObject = new CorrectJsonObject("删除成功");
            return JSONObject.toJSONString(correctJsonObject);
        } else {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(112, "删除失败");
            return JSONObject.toJSONString(errorJsonObject);
        }
    }


    /**
     * 动态图片上传入口
     *
     * @param request 用户请求
     * @param image   图片
     * @return 结果json
     */
    @ResponseBody
    @RequestMapping(value = "/image-upload", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public String dynamicImageUpload(HttpServletRequest request, @RequestBody(required = false) String image) {
        System.out.println("image为：" + image + " end ");
        ErrorJsonObject errorJsonObject;
        //指定头类型
        String headerPng = "data:image/png;base64,";
        String headerJpG = "data:image/jpeg;base64,";

        //获取服务器的路径
        String realPath = request.getSession().getServletContext().getRealPath("/resources/dynamicImg");

        System.out.println("realPath为：" + realPath + "  end");
        //声明图片地址
        String imgAddress = null;
        //获取扩展名
        String extensionName = ".png";
        System.out.println("--------------- >" + extensionName);
        if (image != null && (image.indexOf(headerPng) != 0 || image.indexOf(headerJpG) != 0)) {
            String headPng = image.substring(0, headerPng.length());
            String headJpG = image.substring(0, headerJpG.length());
            if (headerJpG.equals(headJpG)) {
                //去掉头部
                image = image.substring(headerJpG.length());
                BASE64Decoder decoder = new BASE64Decoder();
                try {
                    if (!image.isEmpty()) {

                        //以当前时间加随机数命名上传文件
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
                        String date = sdf.format(new java.util.Date());


                        //设置图片名为当前时间加随机数
                        imgAddress = date + new Random().nextInt() + extensionName;

                        //将文件上传到服务器
                        byte[] decodedBytes = decoder.decodeBuffer(image);

                        FileOutputStream out = new FileOutputStream(realPath + "/" + imgAddress);

                        out.write(decodedBytes);

                        out.close();

                        CorrectJsonObject correctJsonObject = new CorrectJsonObject(" 上传成功");
                        correctJsonObject.setData(imgAddress);
                        return correctJsonObject.toString();

                    } else {

                        errorJsonObject = new ErrorJsonObject(108, "上传的图片不存在！");
                        return errorJsonObject.toJSONString();

                    }
                } catch (IOException e) {

                    errorJsonObject = new ErrorJsonObject(108, e.getMessage());
                    return errorJsonObject.toJSONString();

                }
            } else if (headerPng.equals(headPng)) {
                //去掉头部
                image = image.substring(headerPng.length());
                BASE64Decoder decoder = new BASE64Decoder();
                try {
                    if (!image.isEmpty()) {

                        //以当前时间加随机数命名上传文件
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
                        String date = sdf.format(new java.util.Date());


                        //设置图片名为当前时间加随机数
                        imgAddress = date + new Random().nextInt() + extensionName;

                        //将文件上传到服务器
                        byte[] decodedBytes = decoder.decodeBuffer(image);

                        FileOutputStream out = new FileOutputStream(realPath + "/" + imgAddress);

                        out.write(decodedBytes);

                        out.close();

                        CorrectJsonObject correctJsonObject = new CorrectJsonObject("上传成功");
                        correctJsonObject.setData(imgAddress);
                        return correctJsonObject.toString();

                    } else {

                        errorJsonObject = new ErrorJsonObject(108, " 上传的图片不存在！");
                        return errorJsonObject.toJSONString();

                    }
                } catch (IOException e) {

                    errorJsonObject = new ErrorJsonObject(108, e.getMessage());
                    return errorJsonObject.toJSONString();

                }
            } else {
                errorJsonObject = new ErrorJsonObject(107, "文件不存在或格式不正确");
                return errorJsonObject.toJSONString();
            }
        } else {
            errorJsonObject = new ErrorJsonObject(107, "文件不存在或格式不正确");
            return errorJsonObject.toJSONString();
        }
    }
}
